#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   draw_one_day_climb.py    
@Contact :   raogx.vip@hotmail.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2021/1/27 23:28   gxrao      1.0         None
'''

# import lib

import csv_tools.real_execl as read
import pandas as pd
import logging
import mocks.mocks_result as mocks
import constdef.pig_climb as const
import utils

# 先配置一下日志级别
logging.basicConfig(level=logging.DEBUG)


def convert_algorithm_result(origin_result):
    for video_name in origin_result:
        pred = origin_result[video_name]["pred"]
        real = origin_result[video_name]["real"]
        length = origin_result[video_name]["length"]
        new_pred = []
        new_real = []

        pred_end = 0
        for p in pred:
            new_pred.extend([0 for x in range(pred_end, p[0])])
            new_pred.extend([1 for x in range(p[0], p[1] + 1)])
            pred_end = p[1] + 1
        if pred_end < length:
            new_pred.extend([0 for x in range(pred_end, length)])

        real_end = 0
        for r in real:
            new_real.extend([0 for x in range(real_end, r[0])])
            new_real.extend([1 for x in range(r[0], r[1] + 1)])
            real_end = r[1] + 1
        if real_end < length:
            new_real.extend([0 for x in range(real_end, length)])

        origin_result[video_name]["pred"] = new_pred
        origin_result[video_name]["real"] = new_real

    return origin_result


def convert_identify_result(origin_result, video_second):
    base = video_second - 1
    new_result = {}
    ab_result = []
    ac_result = []
    ad_result = []
    bc_result = []
    bd_result = []
    cd_result = []

    for times in origin_result:
        classify = round(times[0] / base, 0)
        if classify == 0:
            ab_result.append([times[0] % base, times[1] % base])
        elif classify == 1:
            ac_result.append([times[0] % base, times[1] % base])
        elif classify == 2:
            ad_result.append([times[0] % base, times[1] % base])
        elif classify == 3:
            bc_result.append([times[0] % base, times[1] % base])
        elif classify == 4:
            bd_result.append([times[0] % base, times[1] % base])
        elif classify == 5:
            cd_result.append([times[0] % base, times[1] % base])

    new_result["AB"] = ab_result
    new_result["AC"] = ac_result
    new_result["AD"] = ad_result
    new_result["BC"] = bc_result
    new_result["BD"] = bd_result
    new_result["CD"] = cd_result

    return new_result


# path = '/Users/bytedance/PycharmProjects/tools/pig_climb/real_clmb_record.xlsx'
path = 'G:/experimentCode/python-tools/pig_climb/real_clmb_record.xlsx'
data = pd.DataFrame(pd.read_excel(path))

data = read.merge_two_columns_by_key(data, 'video_num', 'objects', '', True)
data = read.get_sequence_info_by_key(data, 'video_num_objects', 'time_bucket')

# 计算人工标记数据
objects = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
real_result = {}
for o in objects:
    sequence_list = []
    total = 0
    for key in const.video_seconds:
        # 获取人工标记数据
        keys = data.keys()
        new_key = key + o
        if new_key in keys:
            items = data[new_key]
            end = 0
            for item in items:
                sequence_list.extend([0 for x in range(end, item[0])])
                sequence_list.extend([1 for x in range(item[0], item[1] + 1)])
                end = item[1] + 1
            if end < const.video_seconds[key]:
                sequence_list.extend([0 for x in range(end, const.video_seconds[key])])
        else:
            sequence_list.extend([0 for x in range(0, const.video_seconds[key])])
    real_result[o] = sequence_list

algorithm_result = convert_algorithm_result(const.algorithm_result)
classify = ["AB", "AC", "AD", "BC", "BD", "CD"]

matrix_infos = {}
mock_result = {}
for c in classify:
    tp = 0
    fp = 0
    fn = 0
    tn = 0
    for video_name in algorithm_result:
        video_result = algorithm_result[video_name]
        pred = video_result["pred"]
        real = video_result["real"]
        matrix_info = mocks.confusion_matrix_info_by_sequence_list(pred, real, classify)[c]
        tp += matrix_info["tp"]
        fp += matrix_info["fp"]
        fn += matrix_info["fn"]
        tn += matrix_info["tn"]

    matrix_infos[c] = {
        "tp": tp,
        "fp": fp,
        "fn": fn,
        "tn": tn,
    }
    '''
    origin_real_list = real_result[c]
    origin_pred_list = mocks.mock_sequence_list_by_confusion_matrix_info(real_result[c], matrix_infos[c])
    real_list = utils.get_time_bucket_by_sequence_list(real_result[c])
    pred_list = utils.get_time_bucket_by_sequence_list(origin_pred_list)
    logging.debug(c + " real result=%s" % real_list)
    logging.debug(c + " mock result=%s" % pred_list)
    logging.debug(c + " acc=%s" % utils.acc(pred_list, real_list, threshold=0.9))
    mock_result["real_" + c] = origin_real_list
    mock_result["pred_" + c] = origin_pred_list
    '''

# result = pd.DataFrame(mock_result)
# result.to_excel('./result.xlsx')

tp = 0
fp = 0
tn = 0
fn = 0
for matrix_key in matrix_infos:
    tp += matrix_infos[matrix_key]["tp"]
    fp += matrix_infos[matrix_key]["fp"]
    fn += matrix_infos[matrix_key]["fn"]
    tn += matrix_infos[matrix_key]["tn"]
matrix_info_total = {
    "tp": tp,
    "fp": fp,
    "fn": fn,
    "tn": tn,
}

for key in algorithm_result:
    origin_real_list = algorithm_result[key]["real"]
    origin_pred_list = mocks.mock_sequence_list_by_confusion_matrix_info(origin_real_list, matrix_info_total,
                                                                         need_add_rand=True)
    real_list = utils.get_time_bucket_by_sequence_list(origin_real_list)
    pred_list = utils.get_time_bucket_by_sequence_list(origin_pred_list)
    logging.debug(key + " real result=%s" % real_list)
    logging.debug(key + " mock result=%s" % pred_list)
    logging.debug(key + " acc=%s" % utils.acc(pred_list, real_list, threshold=0.9))
